﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace PMS.Controllers
{
    public class AuditController : Controller
    {
      
        //
        // GET: /Audit/

        //public void GetReviewData()
        //{
        //    int reviewId = Commons.String2Int32(Request.QueryString["reviewId"]);
        //    BD_ReviewTotal reviewTotal = BLLSession.Current.BD_ReviewTotalBLL.GetListBy(r => r.ID == reviewId).FirstOrDefault();
        //    if (reviewTotal == null)
        //    {
        //        reviewTotal = new BD_ReviewTotal() { RevNum = "空", AddPerson = "空" };
        //    }
        //    List<BD_ReviewDetail> reviewDetail = BLLSession.Current.BD_ReviewDetailBLL.GetListBy(r => r.ReviewerId == reviewId, r => r.RevGroup, true).ToList();
        //    List<BD_ReviewDetail> detailLow = reviewDetail.Where(r => r.IsLeadOrDep == "0").ToList();
        //    List<BD_ReviewDetail> detailHigh = reviewDetail.Where(r => r.IsLeadOrDep == "1").OrderBy(r => r.RevGroup).ToList();
        //    List<string> groupLow = new List<string>();
        //    List<string> groupHigh = new List<string>();
        //    detailLow.ForEach(r => { if (!groupLow.Contains(r.RevGroup)) { groupLow.Add(r.RevGroup); } });
        //    detailHigh.ForEach(r => { if (!groupHigh.Contains(r.RevGroup)) { groupHigh.Add(r.RevGroup); } });
        //    UserInfo basic = OperateContext.sessUserInfo;
        //    Response.Write(JsonHelper.toJson(new { reviewTotal = reviewTotal, reviewDetail = reviewDetail, detailLow = detailLow, detailHigh = detailHigh, groupLow = groupLow, groupHigh = groupHigh, basic = basic }));
        //}
        /// <summary>
        /// 获取我的待审任务
        /// </summary>
        public void GetMyReviewTask()
        {
            string userId = "," + OperateContext.sessUserInfo.Id.ToString() + ",";
            List<BD_ReviewTotal> list = BLLSession.Current.BD_ReviewTotalBLL.GetListBy(r => r.TotalState == "3" && r.CurrentReviewer.Contains(userId)).ToList();
            Response.Write(JsonHelper.toJson(list));
        }

        /// <summary>
        /// 开始审批
        /// </summary>
        public void BeginReview()
        {
            if (Request.Form["RevId"] != null)
            {
                int RevId = Commons.String2Int32(Request.Form["RevId"]);
                string AddPerAdv = Request.Form["AddPerAdv"];
                List<BD_ReviewDetail> detailRev = BLLSession.Current.BD_ReviewDetailBLL.GetListBy(r => r.ReviewerId == RevId).ToList();
                List<BD_ReviewDetail> newDetailRev = new List<BD_ReviewDetail>() { };
                BD_ReviewTotal totalRev = BLLSession.Current.BD_ReviewTotalBLL.GetListBy(t => t.ID == RevId).FirstOrDefault();
                List<View_BD_UserDepInfo> userList = UserRelate.GetAllUsers();

                string allReviewName = "";
                foreach (var item in detailRev)
                {
                    string id = item.ID.ToString();
                    if (Request.Form["per" + id] != null)
                    {
                        if (Request.Form["per" + id].ToString() == "")
                        {
                            Response.Write(JsonHelper.toDefaultMsg(false, "请选择审批人！"));
                            return;
                        }
                        int userId = Commons.String2Int32(Request.Form["per" + id]);
                        item.Reviewer = userId;
                        var user = userList.Where(u => u.ID == userId).FirstOrDefault();
                        if (user != null)
                        {
                            item.ReviewerName = user.UserName;
                            allReviewName += item.ReviewerName + ",";
                            newDetailRev.Add(item);
                        }
                    }
                    else
                    {
                        BLLSession.Current.BD_ReviewDetailBLL.Del(item);
                    }
                }
                totalRev.AddPerAdv = AddPerAdv;
                totalRev.AllRevName = allReviewName.Trim(',');
                Audit.BeginAudit(totalRev, newDetailRev, userList);

                Response.Write(JsonHelper.toDefaultMsg(true, "提交审批成功，该流程已启动！"));
            }
        }
        /// <summary>
        /// 当前审批人提交审批结果
        /// </summary>
        public void SubmitReview()
        {
            ReviewResult revResult = new ReviewResult();
            ModelTools.Form2EditModel(Request.Form, revResult);
            List<BD_ReviewDetail> detailRev = BLLSession.Current.BD_ReviewDetailBLL.GetListBy(r => r.ReviewerId == revResult.RevId).ToList();
            BD_ReviewTotal totalRev = BLLSession.Current.BD_ReviewTotalBLL.GetListBy(t => t.ID == revResult.RevId).FirstOrDefault();
            List<View_BD_UserDepInfo> userList = UserRelate.GetAllUsers();
            Message msg = Audit.SubmitAudit(revResult, totalRev, detailRev, userList);
            Response.Write(JsonHelper.toJson(msg));
        }
        ///// <summary>
        ///// 获取所有审核任务列表
        ///// </summary>
        //public void GetReviewList()
        //{
        //    List<SearchCondition> listSearch = new List<SearchCondition>();
        //    if (Request.Form["searchData"] != null)
        //    {
        //        string searchData = Request.Form["searchData"];
        //        listSearch = ModelTools.GetSearchContions(searchData);
        //        if (listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault() != null)
        //        {
        //            listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault().Field = "FillDate";
        //        }
        //        if (listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault() != null)
        //        {
        //            listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault().Field = "FillDate";
        //        }
        //    }
        //    Expression<Func<View_BD_ReviewTotal, bool>> exp = SearchExpression.FindByGroup<View_BD_ReviewTotal>(listSearch);
        //    int count = 0;
        //    var list = BLLSession.Current.View_BD_ReviewTotalBLL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, u=>u.FillDate, OperateContext.OrderDesc);
        //    count = BLLSession.Current.View_BD_ReviewTotalBLL.GetCount(exp);
        //    List<int> perInt = OperateContext.SessPermission.Select(p => p.Id).ToList();
        //    list.ForEach(r =>
        //    {
        //        if (perInt.Contains((int)r.PermissionId))
        //        {
        //            r.CanReview = "0";
        //        }
        //        else
        //        {
        //            r.CanReview = "1";
        //        }
        //    });

        //    Response.Write(JsonHelper.toPageJson(list, count));
        //}
        /// <summary>
        /// 反审某条任务
        /// </summary>
        public void BackAudit()
        {
            int reviewId = Commons.String2Int32(Request.QueryString["reviewId"]);
            List<BD_ReviewDetail> detailRev = BLLSession.Current.BD_ReviewDetailBLL.GetListBy(r => r.ReviewerId == reviewId).ToList();
            BD_ReviewTotal totalRev = BLLSession.Current.BD_ReviewTotalBLL.GetListBy(t => t.ID == reviewId).FirstOrDefault();

            var revdoc = BLLSession.Current.BD_RevDocInfoBLL.GetListBy(r => r.ID == totalRev.DocId).FirstOrDefault();
            if (!string.IsNullOrEmpty(revdoc.CanBackMethod))
            {
                Type auditClass = Type.GetType("PMS." + revdoc.Class);
                string method = revdoc.CanBackMethod;
                MethodInfo mf = auditClass.GetMethod(method, BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(BD_ReviewTotal), typeof(List<BD_ReviewDetail>) }, null);
                Message msg = mf.Invoke(null, new object[] { totalRev, detailRev }) as Message;
                if (msg.state == "success")
                {
                    Audit.BackReview(totalRev, detailRev);
                    Response.Write(JsonHelper.toDefaultMsg(true, "反审成功,请重新编辑该单据！"));
                }
                else
                {
                    Response.Write(JsonHelper.toJson(msg));
                }
            }
            else
            {
                Audit.BackReview(totalRev, detailRev);
                Response.Write(JsonHelper.toDefaultMsg(true, "反审成功,请重新编辑该单据！"));
            }


        }

        /// <summary>
        /// 被驳回的单据重新初始化
        /// </summary>
        public void ResetReview()
        {
            int reviewId = Commons.String2Int32(Request.Form["reviewId"]);
            List<BD_ReviewDetail> detailRev = BLLSession.Current.BD_ReviewDetailBLL.GetListBy(r => r.ReviewerId == reviewId).ToList();
            BD_ReviewTotal totalRev = BLLSession.Current.BD_ReviewTotalBLL.GetListBy(t => t.ID == reviewId).FirstOrDefault();
            Audit.ResetReview(totalRev, detailRev);
            Response.Write(JsonHelper.toDefaultMsg(true, "初始化成功,请重新编辑该单据！"));
        }



        //获取审批下拉选人
        public void GetAuditPeo()
        {
            string type = Request.QueryString["type"];
            int detailId = Commons.String2Int32(Request.QueryString["detailId"]);
            if (type == "low")
            {
                Response.Write(JsonHelper.toJson(BLLSession.Current.BD_RevUserInfoBLL.GetListBy(r => r.depRevInfoId == detailId).Select(r => new { value = r.userId, text = r.userName })));
            }
            else if (type == "high")
            {
                Response.Write(JsonHelper.toJson(BLLSession.Current.BD_RevDepInfoBLL.GetListBy(r => r.ledRevInfoId == detailId).Select(r => new { value = r.userId, text = r.userName })));
            }

        }

        public void ChechIsBeginAudit()
        {
            int reviewId = Commons.String2Int32(Request.Form["reviewId"]);
            var reviewTotal = BLLSession.Current.BD_ReviewTotalBLL.GetListBy(r => r.ID == reviewId).FirstOrDefault();
            if (reviewTotal != null)
            {
                if (reviewTotal.TotalState == "3")
                {
                    var reviewDetail = BLLSession.Current.BD_ReviewDetailBLL.GetListBy(r => r.ReviewerId == reviewId && r.RevState == "1").ToList();
                    if (reviewDetail.Count == 0)
                    {
                        Response.Write(JsonHelper.toDefaultMsg(true, "success"));
                    }
                    else
                    {
                        Response.Write(JsonHelper.toDefaultMsg(false, "该单据开始审批，无法反审"));
                    }
                }
                else
                {
                    Response.Write(JsonHelper.toDefaultMsg(false, "该单据无法反审"));
                }
            }
            else
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "该单据无法反审"));
            }
        }
    }
}
